package edu.suda.LoopCodePlus.controller;
import com.auth0.jwt.interfaces.DecodedJWT;
import edu.suda.LoopCodePlus.common.Result;
import edu.suda.LoopCodePlus.entity.SubmissionRecord;
import edu.suda.LoopCodePlus.service.ProblemService;
import edu.suda.LoopCodePlus.service.RunService;
import edu.suda.LoopCodePlus.service.SubmissionService;
import edu.suda.LoopCodePlus.service.UserService;
import edu.suda.LoopCodePlus.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.Map;


@RestController
@RequestMapping("/run")
@Slf4j
public class RunController {
    @Autowired
    private RunService runService;
    @Autowired
    private ProblemService problemService;
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private SubmissionService submissionService;

    /*****
     *
     * @param data
     * @return
     * 状态码标识：
     * 0：成功 1：超时 -1：用户不存在 -3：题目不存在 -2：代码未输入 2：运行错误 3：编译错误 4：答案错误 -4提交记录有误
     */
    @PostMapping("python")
    public Result python(@RequestBody Map<String,Object> data,
                         HttpServletRequest request,
                         HttpServletResponse response) {
        System.out.println("验证token");
        String token = request.getHeader("Authorization");
        try {
            DecodedJWT decodedJWT = jwtUtil.verifyToken(token);
            System.out.println("token验证成功");
        }catch (Exception e){
            System.out.println("token验证失败");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return null;
        }
        System.out.println("参数校验中");
        Integer userId = (Integer) data.get("userId");
        System.out.println("userId:"+userId);
        if(userId == null||userService.findUserById(userId)==null) return Result.failure("[{},\"用户不存在\",-1,\"\"]");
        Integer problemId = (Integer) data.get("problemId");
        if(problemId == null||problemService.findProblemById(problemId)==null) return Result.failure("[{},\"题目不存在\",-3,\"\"]");
        String code = (String) data.get("code");
        if(code == ""||code==null) return Result.failure("[{},\"未输入任何代码\",-2,\"\"]");
        //参数校验通过，开始运行代码
        System.out.println("判题开始");
        String cases=problemService.findProblemById(problemId).getTestCase();
        String result = "";
        try {
            result = runService.runPythonCode(code, problemId);
            //去除result最后面的\r\n
            result = result.substring(0,result.length()-2);
            result = result.replace("True","true");
            result = result.replace("False","false");
            System.out.println("运行结束,运行结果:"+result);
            System.out.println(result);
        } catch (Exception e) {
            System.out.println("运行结束,运行结果:"+e.getMessage());
            String a=e.getMessage();
            //将a转为字符串，使其在一行输出
            a=a.replace("\r\n","$");
            a=a.replaceAll("\\\\","/");
            a=a.replace("\"","'");
            SubmissionRecord submissionRecord1;
            try {
                System.out.println("将提交记录插入数据库表:");
                System.out.println("判题结束");
                System.out.println("将用户本次提交记录插入:");
                submissionRecord1 = SubmissionRecord.builder()
                        .userId(userId)
                        .problemId(problemId)
                        .submit(code)
                        .returnValue("[{},\""+ a +"\",3,\"\"]")
                        .recordType(1)
                        .point(0)
                        .comId(6)
                        .build();
                System.out.println(submissionRecord1);
                System.out.println("提交记录生成成功");
            }catch (Exception e1){
                System.out.println(e1.getMessage());
                System.out.println("提交记录生成失败");
                return Result.failure("[{},\"提交记录生成失败\",-4,\"\"]");
            }
            try{
                if(submissionService.insertSubmissionRecord(submissionRecord1)){
                    System.out.println("提交记录插入成功");
                }
                else{
                    System.out.println("提交记录插入失败");
                    return Result.failure("[{},\"提交记录插入失败\",-4,\"\"]");
                }
            }catch (Exception e2){
                System.out.println("提交记录插入失败");
                return Result.failure("[{},\"提交记录插入失败\",-4,\"\"]");
            }
            return Result.failure("[{},\""+ a +"\",3,\"\"]");
        }
        //将result解析为数组,插入提交记录
        SubmissionRecord submissionRecord;
        try {
            System.out.println("将提交记录插入数据库表:");
            JSONArray resultArray = new JSONArray(result);
            Integer point = resultArray.getInt(4);
            System.out.println("判题结束");
            System.out.println("将用户本次提交记录插入:");
            submissionRecord = SubmissionRecord.builder()
                    .userId(userId)
                    .problemId(problemId)
                    .submit(code)
                    .returnValue(result)
                    .recordType(1)
                    .point(point)
                    .comId(6)
                    .build();
            System.out.println(submissionRecord);
            System.out.println("提交记录生成成功");
        }catch (Exception e){
            System.out.println("提交记录生成失败");
            return Result.failure("[{},\"提交记录生成失败\",-4,\"\"]");
        }
        try{
            if(submissionService.insertSubmissionRecord(submissionRecord)){
                System.out.println("提交记录插入成功");
                return Result.success(result);
            }
            else{
                System.out.println("提交记录插入失败");
                return Result.failure("[{},\"提交记录插入失败\",-4,\"\"]");
            }
        }catch (Exception e){
            System.out.println("提交记录插入失败");
            return Result.failure("[{},\"提交记录插入失败\",-4,\"\"]");
        }
    }
}